package tasks

import contributors.*
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch

//实现同步，若是使用修改共享数据来更新的话会易于出错且维护繁琐，为此可以使用Channel实现
suspend fun loadContributorsChannels(
    service: GitHubService,
    req: RequestData,
    updateResults: suspend (List<User>, completed: Boolean) -> Unit
) = coroutineScope {
    val repos = service.getOrgRepos(req.org)
        .also { logRepos(req, it) }
        .body() ?: emptyList()
    val channel = Channel<List<User>>()
//    var isCompleted = false
    repos.forEachIndexed { index, repo ->
        //这里不需要用到async的Deferred结果去await
        launch {
            val users = service.getRepoContributors(req.org, repo.name)
                .also { logUsers(repo, it) }
                .body() ?: emptyList()
//            isCompleted = index == repos.lastIndex
            channel.send(users)
        }
    }
    val results = mutableListOf<User>()
    repeat(repos.size) {
        results.addAll(channel.receive())
        updateResults(results.aggregate(), it == repos.lastIndex)
    }
}
